import os
import threading

from flasgger import Swagger

from apps.app_vedio_playbook import app_video_creator
from common.json_flask import JsonFlask
from common.json_response import JsonResponse
from model.models import db
from apps.app_vedio_playbook  import video_create_q, create_video
from jobs import backend_schedule_jobs

from configs import configs_service

# app = Flask(__name__)


app = JsonFlask(__name__)

app.config['JSON_AS_ASCII'] = False
app.register_blueprint(app_video_creator)
# app.config['JWT_SECRET_KEY'] = 'uk-writer-aigc'  # 替换为你的密钥
# app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(minutes=24*60)  # 设置JWT的默认过期时间为10分钟
# app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=30)
app.config['SWAGGER'] = {
    'title': 'UK WRITER AIGC - VIDEO SERVER',
    'description': 'API for Gen AI',
    'version': '1.0.0',
    'contact': {
        'name': 'xj',
        'email': 'xj@example.com',
        'url': 'https://www.example.com/'
    },
    'license': {
        'name': 'Apache 2.0',
        'url': 'http://www.apache.org/licenses/LICENSE-2.0.html'
    }
}
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@192.168.11.153:3306/uk_writer'
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://bec:Bec123456@rm-bp1lwsq8otehfl1vtdo.mysql.rds.aliyuncs.com:3306/uk_writer'
app.config['SQLALCHEMY_DATABASE_URI'] = configs_service.get_config('mysql_endpoint')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['MAX_CONTENT_LENGTH'] = 175 * 1024
os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] = "LTAI5tQm45eQJuCZ3U5t6Ltt"
os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] = "wUSxy0RTAvAi5s6eml6NW5yH2v0CRS"
os.environ['ALIBABA_CLOUD_OCR_ACCESS_KEY_ID'] = "cknvrCDrXfZ1Tf0U"
os.environ['ALIBABA_CLOUD_OCR_ACCESS_KEY_SECRET'] = "FF73JkJFPiBRtaPTRpxlku5uWvPVKB"
# jwt = JWTManager(app)
swagger = Swagger(app)
# 连接数据库
db.init_app(app)
# 初始化初始化向量数据库异步插入任务线程
# chroma_store_consumer_thread = threading.Thread(target=chroma_store_consumer)
# chroma_store_consumer_thread.start()
# chroma_store_q.join()

#开始创建视频任务消息消费者
def create_video_task_consumer():
    while True:
        with app.app_context():
            create_video()

num_consumers = 2
for i in range(num_consumers):
    create_video_task_consumer_t = threading.Thread(target=create_video_task_consumer)
    create_video_task_consumer_t.start()
    video_create_q.join()

backend_schedule_jobs.scheduler.start()

@app.errorhandler(Exception)
def error_handler(e):
    """
    全局异常捕获，也相当于一个视图函数
    """
    print(str(e))
    return JsonResponse.error(msg=str(e))


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5009)
